package com.zhkj.txg.module.member.ui

import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.Observer
import com.zhkj.lib.base.ViewModelFragment
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.lib.utils.AccountManager
import com.zhkj.txg.R
import com.zhkj.txg.module.member.vm.MemberCardViewModel

class MemberFragment : ViewModelFragment<MemberCardViewModel>() {
    override fun setViewModel(): MemberCardViewModel = createViewModel(true)
    override val layoutResId: Int = R.layout.fragment_member

    private val memberDetailFragment: MemberDetailFragment by lazy { MemberDetailFragment() }
    private val memberProductFragment: MemberProductFragment by lazy { MemberProductFragment() }
    private var refresh = false

    override fun initViewModel() {
        viewModel.memberCardLiveData.observe(viewLifecycleOwner, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) response.response?.data?.let {
                showFragment(if (it.isMember) memberDetailFragment else memberProductFragment)
            }
        })
        // 切换账户观察者
        viewModel.accountChangeSubscribe().observe(viewLifecycleOwner, Observer { refresh = true })
        // 会员状态变动观察者
        viewModel.memberStatusChangeSubscribe().observe(viewLifecycleOwner, Observer { refresh = true })
    }

    override fun initData() {
        viewModel.getMemberCard(AccountManager.getToken())
    }

    override fun onResume() {
        super.onResume()
        if (refresh) {
            initData()
            refresh = false
        }
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden && refresh) {
            initData()
            refresh = false
        }
    }

    private fun showFragment(fragment: Fragment) {
        childFragmentManager.beginTransaction().apply {
            childFragmentManager.fragments.forEach { hide(it) }
            if (!fragment.isAdded) add(R.id.containerMember, fragment)
                .setMaxLifecycle(fragment, Lifecycle.State.RESUMED)
        }.show(fragment).commit()
    }
}